package com.yiqi.news.mvp.presenter

import android.app.Application

import com.jess.arms.integration.AppManager
import com.jess.arms.di.scope.FragmentScope
import com.jess.arms.mvp.BasePresenter
import com.jess.arms.http.imageloader.ImageLoader
import com.yiqi.news.app.base.ActivityLifeCycle.formattime
import com.yiqi.news.app.utils.RxUtils
import com.yiqi.news.entity.BaseResponse
import com.yiqi.news.entity.User
import me.jessyan.rxerrorhandler.core.RxErrorHandler
import javax.inject.Inject

import com.yiqi.news.mvp.contract.UserContract
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber
import kotlin.text.Typography.times


@FragmentScope
class UserPresenter
@Inject
constructor(model: UserContract.Model, rootView: UserContract.View) :
        BasePresenter<UserContract.Model, UserContract.View>(model, rootView) {
    @Inject

    lateinit var mErrorHandler: RxErrorHandler
    @Inject
    lateinit var mApplication: Application
    @Inject
    lateinit var mImageLoader: ImageLoader
    @Inject
    lateinit var mAppManager: AppManager


    override fun onDestroy() {
        super.onDestroy()
    }

    fun getUser() {
        mModel.getUser()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxUtils.applySchedulers(mRootView))
                .subscribe(object : ErrorHandleSubscriber<BaseResponse<User>>(mErrorHandler) {
                    override fun onNext(t: BaseResponse<User>) {
                        if (t.isSuccess) {
                            mRootView.showUser(t.data)
                        } else {
                            mRootView.showError(t.msg)
                        }
                    }


                })
    }

    /**
     * 添加金币
     *
     * isReadEnd：是否阅读完（阅读完需要添加金币）
     */
    fun readNews(times: Long, isReadEnd: Boolean) {
        var time = formattime(times)
        mModel.readNews(time, isReadEnd)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxUtils.applySchedulers(mRootView))
                .subscribe(object : ErrorHandleSubscriber<BaseResponse<User>>(mErrorHandler) {
                    override fun onNext(t: BaseResponse<User>) {
                        if (t.isSuccess) {
                            getUser()
                        } else {
                            mRootView.showError(t.msg)
                        }
                    }


                })
    }


}
